package com.itzxx.huazhun.network

import com.itzxx.huazhun.data.repository.HttpRequestCoroutine
import com.itzxx.huazhun.data.repository.HttpRequestManger
import com.itzxx.huazhun.utils.UserCacheHelper
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

class TokenInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        val response = chain.proceed(originalRequest) //执行此次请求
        if (response.code == 401) { //返回为token失效
            //失效就清除
            UserCacheHelper.putToken("")
            HttpRequestCoroutine.doRefreshToken()
            val newRequest = chain.request()
                .newBuilder()
                .header(
                    "Authorization",
                    "Bearer ${UserCacheHelper.getToken()}"
                )
                .build() //
            return chain.proceed(newRequest)
        }
        return response
    }

}